import random
from datetime import datetime
import requests
from qiniu import *


# 调用示例


access_key = 'your_access_key'
secret_key = 'your_secret_key'
bucket_name = 'your_bucket_name'
domain = 'your_domain'



def upload_to_qiniu(url, type):

    file_name = get_file_name(type)
    # 创建 Auth 对象
    auth = Auth(access_key, secret_key)

    # 生成上传 Token
    token = auth.upload_token(bucket_name, file_name)

    # 从链接下载文件数据
    response = requests.get(url)
    file_data = response.content

    # 上传文件数据
    ret, info = put_data(token, file_name, file_data)

    # 打印上传结果信息
    print(ret)
    print(info)
    # 构建文件访问链接
    if 'key' in ret:
        file_key = ret['key']
        file_url = f"{domain}/{file_key}"  # 替换为实际的文件访问链接
        return file_url
    else:
        return None


def get_file_name(type):
    # 格式化当前时间
    formatted_name = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + "_" + generate_random_numbers(6) + "." + type
    return formatted_name


def generate_random_numbers(length):
    # 生成指定长度的随机数字串
    random_numbers = [str(random.randint(0, 9)) for _ in range(length)]

    # 组合随机数字为字符串
    random_numbers_string = ''.join(random_numbers)

    return random_numbers_string


if __name__ == '__main__':
   url = upload_to_qiniu("https://mmbiz.qpic.cn/mmbiz_png/ibQ2cXpBDzUNwMa2x7AtzVF1qLLNsQmqgGYUuOZxrQiavO6DmZOmwBudmjmg6jkJEpAJJAutmgmUiaYn4obZH0WtQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1", "png")
   print(url)
